package com.jh.paymentchannel.service;

//import static org.hamcrest.CoreMatchers.nullValue;
//import static org.junit.Assert.fail;

import java.math.BigDecimal;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import com.jh.paymentchannel.pojo.JFCoinRegister;
import org.apache.commons.codec.digest.DigestUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.jh.paymentchannel.business.BranchbankBussiness;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.jifuquick.AES;
import com.jh.paymentchannel.util.jifuquick.Base64;
import com.jh.paymentchannel.util.jifuquick.HttpClient4Util;

import net.sf.json.JSONObject;

@Controller
@EnableAutoConfiguration
public class JFCoinpageRequest {

	private static final Logger log = LoggerFactory.getLogger(JFCoinpageRequest.class);



	@Autowired
	private TopupPayChannelBusiness topupPayChannelBusiness;

	@Autowired
	private BranchbankBussiness branchbankBussiness;

	@Autowired
	private Util util;

	@Value("${payment.ipAddress}")
	private String ipAddress;
	
	@Value("${jfcoin.partnerNo}")
	private String partnerNo;
	
	@Value("${jfcoin.key}")
	private String Key;
	
	@Value("${jfcoin.url}")
	private String JFurl;
	
	
	private static final Charset UTF_8 = StandardCharsets.UTF_8;
	
	/**
	 * 进件接口
	 *
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfcoin/register")
	public @ResponseBody Object jfCoinRegister(HttpServletRequest request,
			@RequestParam(value = "ordercode") String ordercode,
			@RequestParam(value = "provinceOfBank") String provinceOfBank,
			@RequestParam(value = "cityOfBank") String cityOfBank,
			@RequestParam(value = "bankBranchName") String bankBranchName,
			@RequestParam(value = "expiredTime",required=false) String expiredTime,
			@RequestParam(value = "securityCode",required=false) String securityCode
		)
		throws Exception {
		log.info("开始进入进件接口========================");
		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		/** 首先拿到用户的userid, 如果用户已经存在，那么直接拿用户的sdjuserid, 如果用户的默认结算卡已经和当前不一样了。 需要重新注册 **/
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "没有该订单信息");
			return map;
		}
		
		
		String realamount = resultObj.getString("realAmount");
		String userid = resultObj.getString("userid");
		// 通道id
		String channelid = resultObj.getString("channelid");
		// 费率
		String rate = resultObj.getString("rate");
		// 额外费率
		String extraFee = resultObj.getString("extraFee");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询默认结算卡出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "查询默认结算卡有误");
			return map;
		}
		String respcode = jsonObject.getString("resp_code");
		if (!"000000".equals(respcode)) {

			maps.put("resp_code", "failed");
			maps.put("channel_type", "jfcoin");
			maps.put("resp_message", "没有结算卡");
			return maps;
		}
		
		// 默认提现卡卡号
		String cardNo = resultObj.getString("cardNo");
		String userName = resultObj.getString("userName");
		/** 身份证号 */
		String idcard = resultObj.getString("idcard");
		String phone = resultObj.getString("phone");
		String bankName = resultObj.getString("bankName");

		
		//随机获取商铺信息表中的商户数据
		//String shopUserId = Util.shops();
		
		restTemplate=new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/query/randomuserid";
		requestEntity  = new LinkedMultiValueMap<String, String>();
		
		String shopUserId;
		try {
			result = restTemplate.postForObject(url, requestEntity, String.class);
			jsonObject =  JSONObject.fromObject(result);
			shopUserId = jsonObject.getString("result");
		} catch (Exception e1) {
			log.error("查询用户ID出错！！！！");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "sdj");
			maps.put("resp_message", "没有查询到用户ID");
			return maps;
		}
		
		log.info("随机获取的userId"+shopUserId);
		
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/shops/query/uid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("userid", shopUserId);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询商铺信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "查询商铺信息有误");
			return map;
		}

		String shopName = resultObj.getString("name");// 商户全称
		String address = resultObj.getString("address");// 注册地址
		String shopsAddress = resultObj.getString("shopsaddress");

		String Address = address + shopsAddress;


		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/shops/find/province";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("userId", shopUserId);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
		} catch (Exception e1) {
			log.error("查询商铺省市信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "查询商铺省市信息有误");
			return map;
		}
		String province = jsonObject.getString("province");
		String city = jsonObject.getString("city");
		
		String orderNo = getNumberOrderCode();
		// 进件接口的交易代码
		String txnCode = "101001";
		String api = "/rest/api/"+txnCode;

		JSONObject dto = new JSONObject();
		
		//生成一个8位随机数
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String merchantCode = uuid.substring(0, 8);
		String substring = uuid.substring(8,11);
		
		String t0TxnFee = "";
		Double valueOf = Double.valueOf(extraFee);
		if(valueOf!=0&&valueOf>0.2){
			String extrafee = new BigDecimal(valueOf.toString()).multiply(new BigDecimal("100")).setScale(0).toString();
			t0TxnFee = extrafee;
		}else{
			t0TxnFee = "20";
		}
		
		dto.put("merchantCode", merchantCode);// 商户号
		dto.put("merchantName", shopName+substring);// 商户名称
		dto.put("shortName", shopName);// 商户简称
		dto.put("tel", phone);// 联系电话
		dto.put("province", province);// 商户所在省份
		dto.put("city", city);// 商户所在城市
		dto.put("address", Address);// 商户所在详细地址
		dto.put("cardHolderName", userName);// 持卡人姓名
		dto.put("mobile", phone);// 手机号
		dto.put("idCard", idcard);// 身份证
		dto.put("inBankCardNo", cardNo);// 入账银行卡号
		dto.put("arriveMode", "T0");// 到账模式
		dto.put("txnRate", rate);// 消费交易手续费扣率
		// Strings.isNullOrEmpty(t0TxnFee) ? "0" : t0TxnFee
		dto.put("t0TxnFee", t0TxnFee);// 单笔消费交易手续费
		dto.put("operateType", "A");// 操作类型(A:新增 M:修改)
		dto.put("extend1", "");// 备用字段
		
		dto.put("head", this.getHead(ordercode, partnerNo, txnCode));
		
		log.info(Key, JFurl, api, dto.toString(), partnerNo, orderNo);
		
		String execute = this.execute(Key, JFurl, api, dto.toString(), partnerNo, ordercode);
		log.info(execute);
				
		com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
        String sign = resJson.getString("signature");
        String res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0,16));
		log.info("res========"+res);
        com.alibaba.fastjson.JSONObject json = JSON.parseObject(res);
        com.alibaba.fastjson.JSONObject head = null;
        String respCode = null;
        String respMsg = null;
		try {
			head = json.getJSONObject("head");
			 //返回状态码
	        respCode = head.getString("respCode");
	        respMsg = head.getString("respMsg");
		} catch (Exception e) {
			log.error("返回值没有head,进件出错==="+res);
			map.put("resp_code", "failed");	
			map.put("channel_type", "jfcoin");
			map.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/jfpayerror");
			return map;
		}
       
        
        //进件成功
        if("000000".equals(respCode)&&"success".equals(respMsg)){
        	//进件成功返回的商户号
        	String platMerchantCode = json.getString("platMerchantCode");
        	
        	JFCoinRegister jfCoinRegister = topupPayChannelBusiness.getJFCoinRegister(Long.parseLong(userid));
        	
        	String fee = Double.valueOf(t0TxnFee)/100+"";
        	
        	if(jfCoinRegister==null){
        		log.info("用户第一次进件======");
        		JFCoinRegister jfc = new JFCoinRegister();
        		jfc.setBankCard(cardNo);
        		jfc.setFee(fee);
        		jfc.setJFCoinUserId(platMerchantCode);
        		jfc.setRate(rate);
        		jfc.setMerchantCode(merchantCode);
        		jfc.setUserId(Long.parseLong(userid));
                
                try {
					topupPayChannelBusiness.createJFCoinRegister(jfc);
				} catch (Exception e) {
					map.put("resp_code", "failed");	
			        map.put("channel_type", "jfcoin");
					map.put("resp_message", "保存首次进件信息失败");
					return map;
				}
        	}else{
        		log.info("用户信息修改后重新进件======");
        		jfCoinRegister.setBankCard(cardNo!=null&&!cardNo.equals("")?cardNo:jfCoinRegister.getBankCard());
                jfCoinRegister.setFee(fee);
                jfCoinRegister.setJFCoinUserId(platMerchantCode!=null&&!platMerchantCode.equals("")?platMerchantCode:jfCoinRegister.getJFCoinUserId());
                jfCoinRegister.setRate(rate!=null&&!rate.equals("")?rate:jfCoinRegister.getRate());
                jfCoinRegister.setMerchantCode(merchantCode!=null&&!merchantCode.equals("")?merchantCode:jfCoinRegister.getMerchantCode());
                
                try {
					topupPayChannelBusiness.createJFCoinRegister(jfCoinRegister);
				} catch (Exception e) {
					map.put("resp_code", "failed");	
			        map.put("channel_type", "jfcoin");
					map.put("resp_message", "保存重新进件信息失败");
					return map;
				}
        	}
        	

			log.info("进件成功================"+res);
	        log.info("开始交易==============");
				
			map = (Map) this.jfCoinPay(request, ordercode,securityCode,expiredTime,provinceOfBank,cityOfBank,bankBranchName);
			return map;
			
			
        }
        
        log.info("进件失败=====");
        map.put("resp_code", "failed");	
        map.put("channel_type", "jfcoin");
		map.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/jfpayerror");
		return map;
        
	}

	
	 
	/*
	 * 支付接口
	 * 
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfcoin/pay")
	public @ResponseBody Object jfCoinPay(HttpServletRequest request,
	 		@RequestParam(value = "ordercode") String ordercode,
	 		@RequestParam(value = "provinceOfBank") String provinceOfBank,
			@RequestParam(value = "cityOfBank") String cityOfBank,
			@RequestParam(value = "bankBranchName") String bankBranchName,
			@RequestParam(value = "expiredTime",required=false) String expiredTime,
			@RequestParam(value = "securityCode",required=false) String securityCode
		)throws Exception {

		log.info("开始进入支付接口========================");
		Map<String, String> maps = new HashMap<String, String>();
		//** 首先拿到用户的userid, 如果用户已经存在，那么直接拿用户的sdjuserid, 如果用户的默认结算卡已经和当前不一样了。 需要重新注册 **//*
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询订单信息出错");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jfcoin");
			maps.put("resp_message", "没有该订单信息");
			return maps;
		}
		String realamount = resultObj.getString("realAmount");
		String userid = resultObj.getString("userid");
		// 通道id
		String channelid = resultObj.getString("channelid");
		// 费率
		String rate = resultObj.getString("rate");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");

		String amount = resultObj.getString("amount");
		
		String desc = resultObj.getString("desc");
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询默认结算卡出错");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jfcoin");
			maps.put("resp_message", "查询默认结算卡有误");
			return maps;
		}

		if (resultObj.isNullObject()) {

			maps.put("resp_code", "failed");
			maps.put("channel_type", "jfcoin");
			maps.put("resp_message", "没有结算卡");
			return maps;
		}
		// 默认提现卡卡号
		String cardNo = resultObj.getString("cardNo");
		
		
		
		restTemplate=new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/bank/default/cardno--RESULT================"+result);
		try {
			jsonObject =  JSONObject.fromObject(result);
			resultObj  =  jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询银行卡信息出错");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jfcoin");
			maps.put("resp_message", "查询银行卡信息有误");
			return maps;
		}
		if(resultObj==null){
			return null;
		}
		String mobile = resultObj.getString("phone"); //预留信用卡手机号码
		String idcard = resultObj.getString("idcard");//身份证号
		String userName = resultObj.getString("userName");//用户姓名
		String bankName = resultObj.getString("bankName");
		
		
		Map mapp = new HashMap();
		
		// 支付接口的交易代码
		String paytxnCode = "102001";
		String payapi = "/rest/api/"+paytxnCode;
		
		
		//根据userid去查询用户进件表
		JFCoinRegister jfCoinRegister = topupPayChannelBusiness.getJFCoinRegister(Long.parseLong(userid));
		//获得用户进件成功返回的商户号
		String jfCoinUserId = jfCoinRegister.getJFCoinUserId();
		String fee2 = jfCoinRegister.getFee();
		
		JSONObject dto = new JSONObject();
		dto.put("platMerchantCode", jfCoinUserId);// 入网成功返回的商户号
		
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		String time = format.format(date);
		
		dto.put("cutDate", time);// 当前日期
		
		dto.put("payBankCardNo", bankCard);// 支付银行卡号
		dto.put("cardHolderName", userName);// 持卡人姓名
		dto.put("mobile", mobile);// 充值卡手机号码
		dto.put("idCard", idcard);// 身份证
		
		dto.put("cvv2", securityCode);// 
		dto.put("validity", expiredTime);// 有效期
		dto.put("pwd", "");// 密码
		
		
		// 将订单总金额转换为以分为单位
		String Amount = new BigDecimal(amount).multiply(new BigDecimal("100")).setScale(0).toString();

		dto.put("txnAmt", Amount);// 订单总金额(以分为单位)
		dto.put("remark", desc);// 商品名称	
		dto.put("head", this.getHead(ordercode, partnerNo, paytxnCode));
		String execute = this.execute(Key, JFurl, payapi, dto.toString(), partnerNo, ordercode);
				
        
        com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
        String sign = resJson.getString("signature");
        String res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0,16));
		
        com.alibaba.fastjson.JSONObject json = JSON.parseObject(res);
        com.alibaba.fastjson.JSONObject head = null;
        String respCode = null;
        String respMsg = null;
        
		try {
			head = json.getJSONObject("head");
			//返回状态码
			respCode = head.getString("respCode");
	        respMsg = head.getString("respMsg");
		} catch (Exception e) {
			log.error("支付信息返回没有head,支付失败==="+res);
			mapp.put("resp_code", "failed");
			mapp.put("channel_type", "jfcoin");
			mapp.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/jfpayerror");
			return mapp;
		}
		
        //支付成功
        if("000000".equals(respCode)&&"success".equals(respMsg)){
        	
        	log.info("支付成功==================="+res);
        	
        	json.getString("orderCode");//0000  表示成功
        	json.getString("orderStatus");//1   表示成功
        	
        	if(null != expiredTime || !"".equals(expiredTime)){
        		String before = expiredTime.substring(0, 2);
        		String after = expiredTime.substring(2, 4);
        		
        		BigDecimal big = new BigDecimal(after);
        		BigDecimal time1 = new BigDecimal("12");
        		
        		int compareTo = big.compareTo(time1);
        		
        		if(compareTo==1){
        			expiredTime=after+before;
        			log.info("即将要保存的expiredTime======"+expiredTime);
        		}
        	}
        	
        	restTemplate = new RestTemplate();
    		uri = util.getServiceUrl("user", "error url request!");
    		url = uri.toString() + "/v1.0/user/bank/update/bynewcardno";
    		requestEntity = new LinkedMultiValueMap<String, String>();
    		requestEntity.add("cardNo", cardNo);
    		requestEntity.add("province", provinceOfBank);
    		requestEntity.add("city", cityOfBank);
    		requestEntity.add("bankBranchName", bankBranchName);
    		requestEntity.add("securityCode", securityCode);
    		requestEntity.add("expiredTime", expiredTime);
    		result = restTemplate.postForObject(url, requestEntity, String.class);

    		log.info("RESULT================" + result);
    		jsonObject = JSONObject.fromObject(result);
    		resultObj = jsonObject.getJSONObject("result");
    		
        	//调用订单查询接口,查询订单是否支付
        	Object jfCoinQuery = this.jfCoinQuery(request, ordercode);
        	
        	//01  表示通道那边订单已支付成功
        	if("01".equals(jfCoinQuery)){
        		restTemplate = new RestTemplate();

    			uri = util.getServiceUrl("transactionclear", "error url request!");
    			url = uri.toString() + "/v1.0/transactionclear/payment/update";

    			// **根据的用户手机号码查询用户的基本信息*//*
    			requestEntity = new LinkedMultiValueMap<String, String>();
    			requestEntity.add("status", "1");
    			requestEntity.add("order_code", ordercode);
    			result = restTemplate.postForObject(url, requestEntity, String.class);

    			log.info("订单状态修改成功===================");

    			// **判断是否有外放的通道的处理， 如果有那么继续回调外放哦*//*
    			uri = util.getServiceUrl("transactionclear", "error url request!");
    			url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";

    			requestEntity = new LinkedMultiValueMap<String, String>();
    			requestEntity.add("order_code", ordercode);
    			result = restTemplate.postForObject(url, requestEntity, String.class);

    			jsonObject = JSONObject.fromObject(result);
    			resultObj = jsonObject.getJSONObject("result");
    			String outMerOrdercode = resultObj.getString("outMerOrdercode");
    			String orderdesc = resultObj.getString("desc");
    			String phone = resultObj.getString("phone");
    			String tranamount = resultObj.getString("amount");
    			String channelTag = resultObj.getString("channelTag");
    			String notifyURL = resultObj.getString("outNotifyUrl");
    			if (outMerOrdercode != null && !outMerOrdercode.equalsIgnoreCase("")) {
    				uri = util.getServiceUrl("channel", "error url request!");
    				url = uri.toString() + "/v1.0/channel/callback/yilian/notify_call";
    				requestEntity = new LinkedMultiValueMap<String, String>();
    				requestEntity.add("merchant_no", phone);
    				requestEntity.add("amount", tranamount);
    				requestEntity.add("channel_tag", channelTag);
    				requestEntity.add("order_desc", URLEncoder.encode(orderdesc, "UTF-8"));
    				requestEntity.add("order_code", outMerOrdercode);
    				requestEntity.add("sys_order", ordercode);
    				requestEntity.add("notify_url", URLEncoder.encode(notifyURL, "UTF-8"));
    				result = restTemplate.postForObject(url, requestEntity, String.class);
    			}

    			log.info("订单已支付!");
    			
    			mapp.put("resp_code", "success");
    			mapp.put("channel_type", "jfcoin");
    			mapp.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/jfcoinpaysuccess");
    			return mapp;
            	
    			
            }else {
            	log.info("支付失败==================="+res);
    			mapp.put("resp_code", "failed");
    			mapp.put("channel_type", "jfcoin");
    			mapp.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/jfpayerror");
    			return mapp;
            }
        }else {
        	log.info("支付失败==================="+res);
			mapp.put("resp_code", "failed");
			mapp.put("channel_type", "jfcoin");
			mapp.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/jfpayerror");
			return mapp;
        }	
	
		
	}
	
	
	
	//订单查询接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfcoin/query")
	public @ResponseBody Object jfCoinQuery(HttpServletRequest request,
	 		@RequestParam(value = "ordercode") String ordercode
			
		)throws Exception {
		
		log.info("开始进入查询接口======");
		// 支付接口的交易代码
		String querytxnCode = "103001";
		String queryapi = "/rest/api/"+querytxnCode;
		
		JSONObject dto = new JSONObject();
		dto.put("oriOrderId", ordercode);//订单号
		
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		String time = format.format(date);
		
		dto.put("cutDate", time);
		
		dto.put("head", this.getHead(ordercode, partnerNo, querytxnCode));
		String execute = this.execute(Key, JFurl, queryapi, dto.toString(), partnerNo, ordercode);
				
        
        com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
        String sign = resJson.getString("signature");
        String res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0,16));
		
        com.alibaba.fastjson.JSONObject json = JSON.parseObject(res);
        
        log.info("json====="+json);
        com.alibaba.fastjson.JSONObject head = null;
        String respCode = null;
        String respMsg = null;
        
        Map mapp = new HashMap();
        
		try {
			head = json.getJSONObject("head");
			 log.info("head====="+head);
			//返回状态码
			respCode = head.getString("respCode");
	        respMsg = head.getString("respMsg");
		} catch (Exception e) {
			log.error("支付信息返回没有head,支付失败==="+res);
			mapp.put("resp_code", "failed");
			mapp.put("channel_type", "jfcoin");
			mapp.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/jfpayerror");
			return mapp;
		}
		
		//查询通道返回的订单状态
		String payStatus = json.getString("payStatus");

		return payStatus;
	}
	
	
	
	protected String execute(String key, String url, String api, String dataJson, String partnerNo, String orderId) {

		log.info("============ 请求报文:" + dataJson);
		String signKey = key.substring(16);
		String dataKey = key.substring(0, 16);
		String sign = DigestUtils.sha1Hex(dataJson + signKey);

		Map<String, String> params = Maps.newHashMap();
		params.put("encryptData", Base64.encode(AES.encode(dataJson, dataKey)));
		params.put("signData", sign);
		params.put("orderId", orderId);
		params.put("partnerNo", partnerNo);
		params.put("ext", "to be or not to be");

		log.info("encryptData : " + params.get("encryptData"));
		log.info("sign : " + params.get("sign"));
		log.info("partnerNo : " + params.get("partnerNo"));

		log.info("============ 请求地址:" + url + api);
		try {
			byte[] resByte = HttpClient4Util.getInstance().doPost(url + api, null, params);
			String resStr = new String(resByte, UTF_8);
			log.info("============ 返回报文原文:" + resStr);
			
			return resStr;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	 
    
	public Object getHead(String ordercode, String partnerNo, String txnCode) {
		JSONObject head = new JSONObject();
		head.put("version", "1.0.0");
		head.put("charset", "UTF-8");
		head.put("partnerNo", partnerNo); // 合作方标识号
		head.put("txnCode", txnCode); // 交易代码
		head.put("orderId", ordercode); // 订单号
		head.put("reqDate", DateTime.now().toString("yyyyMMdd"));
		head.put("reqTime", DateTime.now().toString("yyyyMMddHHmmss"));
		return head;
	}
	
	
	
	public static String getNumberOrderCode(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date now = new Date();
		StringBuffer sb = new StringBuffer(sdf.format(now));
		Random random = new Random();
		for(int i = 0;i < 18;i++){
			sb.append(random.nextInt(10));
		}
		return sb.toString();
	}
	
}